//THANKS RATE AND STAR AJAX
//r.583
//адаптация Dr_Brown
# 
#-----[ SQL QUERY ]---------------------------------
# 
ALTER TABLE `bb_attachments_desc` ADD (
`thanks` mediumint( 8 ) NOT NULL default '0',
`rating_sum` int(11) NOT NULL default '0',
`rating_count` mediumint(8) NOT NULL default '0'
);

CREATE TABLE `bb_attachments_rating` (
  `attach_id` mediumint(8) unsigned NOT NULL default '0',
  `user_id` mediumint(9) NOT NULL default '0',
  `thanked` tinyint(1) NOT NULL default '0',
  `rating` tinyint(1) NOT NULL default '0',
  PRIMARY KEY  (`attach_id`,`user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

# 
#-----[ OPEN ]---------------------------------
# 

includes/init_bb.php

# 
#-----[ FIND ]---------------------------------
#

define('BB_ATTACHMENTS',          'bb_attachments');

# 
#-----[ AFTER, ADD ]---------------------------------
#

//Thanks mod
define('BB_ATTACHMENTS_RATING',   'bb_attachments_rating');
//end

# 
#-----[ OPEN ]---------------------------------
# 
templates/default/viewtopic_attach.tpl	  

# 
#-----[ FIND ]---------------------------------
#

<td width="15%" rowspan="4" class="tCenter pad_6">

# 
#-----[ REPLACE WITH ]---------------------------------
#

<td width="15%" rowspan="6" class="tCenter pad_6">

# 
#-----[ FIND ]---------------------------------
#

	<tr class="row1">
		<td>{L_SIZE}:</td>
		<td>{postrow.attach.tor_reged.TORRENT_SIZE}</td>
	</tr>

# 
#-----[ AFTER, ADD ]---------------------------------
#

	<tr class="row1">
        <td class="genmed">{L_RATING}:&nbsp;</td>
        <td class="genmed">{postrow.attach.tor_reged.RATING}<div class="voted" >({L_RATING_VOTES}: {postrow.attach.tor_reged.RATING_VOTES})<!-- IF postrow.attach.tor_reged.YOUR_VOTE -->{postrow.attach.tor_reged.YOUR_VOTE}<!-- ENDIF --></div>
        </td>
    </tr>
    <tr class="row1">
        <script language="JavaScript" type="text/javascript" src="./misc/js/ajax.js"></script>
        <link rel="stylesheet" href="./misc/css/rating.css" type="text/css" />
        <td>{L_THANKED}:</td>
        <td>{postrow.attach.tor_reged.THANKED}</td>
    </tr>

# 
#-----[ OPEN ]---------------------------------
# 
templates/default/usercp_viewprofile.tpl

# 
#-----[ FIND ]---------------------------------
#

					<!-- IF SHOW_PASSKEY -->
					[ {L_BT_PASSKEY}:  <span id="passkey-btn"><a class="med" href="#" onclick="$('#passkey-gen').show(); $('#passkey-btn').hide(); return false;">{L_BT_PASSKEY_VIEW}</a></span>
					<span id="passkey-gen" class="med" style="display: none;">
						<b id="passkey" class="med bold">{AUTH_KEY}</b>&nbsp;
				        <a href="#" onclick="ajax.exec({ action: 'gen_passkey', user_id  : {PROFILE_USER_ID} }); return false;">{L_BT_GEN_PASSKEY}</a>
					</span> ]
					<!-- ENDIF -->
			    </td>
		    </tr>

# 
#-----[ AFTER, ADD ]---------------------------------
#

			<tr>
				<th>{L_THANK}<b>/</b>{L_THANKED}:</th>
				<td id="u_thanks" class="gen">
					{USER_THANKS_} / {USER_THANKED_}
				</td>
			</tr>

# 
#-----[ OPEN ]---------------------------------
# 
language/lang_russian/lang_main.php

# 
#-----[ в конец ]---------------------------------
#

//Thanks mod
$lang['USER_THANKS'] = 'Спасибы пользователя' ;
$lang['USER_THANKS_'] = 'Пользователь сказал спасибо:' ;
$lang['USER_THANKED'] = 'Пользователю сказали спасибо:' ;
$lang['THANKED'] = 'Поблагодарили';
$lang['THANK'] = 'Поблагодарил(a)';
$lang['THANKS'] = 'Спасибо';
$lang['THANK_LIST'] = 'список';
//
$lang['RATING'] = 'Оценка';
$lang['RATING_VOTES'] = 'Голосов';
$lang['YOUR_VOTE'] = 'Ваша оценка';
$lang['VOTE_COUNTED'] = 'засчитана';
//
$lang['RATING_1'] = 'Отстой';
$lang['RATING_2'] = 'Так себе';
$lang['RATING_3'] = 'Средне';
$lang['RATING_4'] = 'Хорошо';
$lang['RATING_5'] = 'Супер';
//End thanks mod

# 
#-----[ OPEN ]---------------------------------
# 
language/lang_english/lang_main.php

# 
#-----[ в конец ]---------------------------------
#

//Thanks mod
$lang['USER_THANKS'] = 'Thanks of the user' ;
$lang['USER_THANKS_'] = 'The user has told thanks:' ;
$lang['USER_THANKED'] = 'To the user have told thanks:' ;
$lang['THANKED'] = 'Have thanked';
$lang['THANK'] = 'Has thanked';
$lang['THANKS'] = 'Thanks';
$lang['THANK_LIST'] = 'List';
//
$lang['RATING'] = 'Rate';
$lang['RATING_VOTES'] = 'Vote';
$lang['YOUR_VOTE'] = 'Your mark';
$lang['VOTE_COUNTED'] = 'It is included';
//
$lang['RATING_1'] = 'Crap';
$lang['RATING_2'] = 'So-so';
$lang['RATING_3'] = 'Average mark';
$lang['RATING_4'] = 'Good';
$lang['RATING_5'] = 'Super';
//End thanks mod

# 
#-----[ OPEN ]---------------------------------
# 
attach_mod/displaying_torrent.php

# 
#-----[ FIND ]---------------------------------
#

$tor_file_time  = bb_date($attachments['_'. $post_id][$i]['filetime']);

# 
#-----[ AFTER, ADD ]---------------------------------
#

//Thanks mod
$rating_sum     = $attachments['_'. $post_id][$i]['rating_sum'];
$rating_count   = $attachments['_'. $post_id][$i]['rating_count'];
$your_vote 		= (!empty($attachments['_'. $post_id][$i]['rating'])) ? $attachments['_'. $post_id][$i]['rating'] : '';
$thanks         = $attachments['_'. $post_id][$i]['thanks'];
$thanked 		= (!empty($attachments['_'. $post_id][$i]['thanked'])) ? $attachments['_'. $post_id][$i]['thanked'] : ''; 

$stars = array('one','two','three','four','five');
    $rate_on = '<ul class="rating';
    if($rating_sum && $rating_count>0) {
        $rate_on .= ' '.$stars[round($rating_sum/$rating_count,1)-1].'star">';
    }
    else {$rate_on .='">';}
    for ($r = 1; $r <= 5; $r++ ) {
        $rate_on .= '<li class="'.$stars[($r-1)].'"><a href="#torrent" title="'.$lang['RATING_'.$r].'" onClick="rate('.$attach_id.','.$r.');"></a></li>';
    }
    $rate_on .='</ul>';

    $rate_off = '<ul class="rating';
    if($rating_sum && $rating_count>0) {
        $rate_off .= ' '.$stars[round($rating_sum/$rating_count,1)-1].'star">';
    }
    else {$rate_off .='">';}
    for ($r = 1; $r <= 5; $r++ ) {
        $rate_off .= '<li class="'.$stars[($r-1)].'"><a href="#torrent" title="'.$lang['RATING_'.$r].'"></a></li>' ;
    }
    $rate_off .='</ul>';
//End

# 
#-----[ FIND ]---------------------------------
#

if ($tor_reged && $tor_info)
{
	$tor_size = ($tor_info['size']) ? $tor_info['size'] : 0;
	$tor_id   = $tor_info['topic_id'];
	$tor_type = $tor_info['tor_type'];

# 
#-----[ AFTER, ADD ]---------------------------------
#

	$rate_html = '';
    
	for ($r = 5; $r >= 1; $r-- ) 
	{
        $rate_html .= '<input type="radio" name="rate'.$attach_id.'" value="'.$r.'" onClick="rate('.$attach_id.','.$r.');" />'
      	. '<span onClick="rate('.$attach_id.','.$r.');">' . $lang['RATING_'.$r] . '</span>';
    }

# 
#-----[ FIND ]---------------------------------
# 
			'COMPLETED'       => sprintf($lang['DOWNLOAD_NUMBER'], $tor_info['complete_count']),

# 
#-----[ AFTER, ADD ]---------------------------------
#

			//Thanks mod
            'RATING'          => '<span id="VR'.$attach_id.'" style="float:left;">'. (($userdata['user_id'] == GUEST_UID || $your_vote > 0) ? $rate_off : $rate_on) .'</span>',
            'RATING_VOTES'    => '<span id="VC'.$attach_id.'">'. $rating_count .'</span>',
            'THANKED'         => '<span id="VT'.$attach_id.'">'. $thanks .'</span>'
            					. ($thanked || ($userdata['user_id'] == $poster_id) ? '' : '<span id="VB'.$attach_id.'">'. '&nbsp; <img src="images/sps.gif" onClick="say_thank(\'thank\',' . $attach_id.');" alt="'. $lang['THANKS'] .'" style="cursor:pointer" /></span>')
            					. ($thanks > 0 ? ' &nbsp; (<span id="VL'.$attach_id.'"><a href="#torrent" onClick="say_thank(\'list\','.$attach_id.');">'. $lang['THANK_LIST'] .'</a></span>)' : ''),
            'YOUR_VOTE'       => '<span id="VD'.$attach_id.'" style="margin-left:5px;">' . ($your_vote > 0 ? $lang['YOUR_VOTE'].': '.$lang['RATING_'.$your_vote]:'') . '</span>',
            //Thanks mod End

# 
#-----[ OPEN ]---------------------------------
#
attach_mod/includes/functions_attach.php

# 
#-----[ FIND ]---------------------------------
#

function get_attachments_from_post($post_id_array)
{
	global $attach_config;

# 
#-----[ IN-LINE AFTER, ADD ]---------------------------------
#
, $userdata	

# 
#-----[ FIND ]---------------------------------
#
	$attachments = array();
	
# 
#-----[ AFTER, ADD ]---------------------------------
#

//Thanks mod
	$user_id = $userdata['user_id'];
//End

# 
#-----[ FIND ]---------------------------------
#

	$sql = 'SELECT a.post_id, d.*
		FROM ' . BB_ATTACHMENTS . ' a, ' . BB_ATTACHMENTS_DESC . " d
		WHERE a.post_id IN ($post_id_array)
			AND a.attach_id = d.attach_id
		ORDER BY d.filetime $display_order";
		
# 
#-----[ REPLACE WITH ]---------------------------------
#

	$sql = 'SELECT a.post_id, d.*'. ($user_id==GUEST_UID ? '' : ', r.thanked, r.rating') .'
		FROM ' . BB_ATTACHMENTS . ' a join ' . BB_ATTACHMENTS_DESC . " d on a.attach_id = d.attach_id"
		. ($user_id==GUEST_UID ? '' : ' left join ' . BB_ATTACHMENTS_RATING . ' r on r.attach_id=a.attach_id and r.user_id=' . $user_id) ."
		WHERE a.post_id IN ($post_id_array)
		ORDER BY d.filetime $display_order";

# 
#-----[ OPEN ]---------------------------------
#
attach_mod/include/functions_delete.php

# 
#-----[ FIND ]---------------------------------
#

			// Delete torrents
			$sql = "DELETE FROM ". BB_BT_TORRENTS ."
				WHERE attach_id IN(". implode(',', $attach_id_array) .")";

			if (!DB()->sql_query($sql))
			{
				message_die(GENERAL_ERROR, $lang['ERROR_DELETED_ATTACHMENTS'], '', __LINE__, __FILE__, $sql);
			}

# 
#-----[ AFTER, ADD ]---------------------------------
#

			// Delete thanks
            $sql = "DELETE FROM ". BB_ATTACHMENTS_RATING ."
                WHERE attach_id IN(". implode(',', $attach_id_array) .")";

            if (!DB()->sql_query($sql))
            {
                message_die(GENERAL_ERROR, $lang['ERROR_DELETED_ATTACHMENTS'], '', __LINE__, __FILE__, $sql);
            }
# 
#-----[ OPEN ]---------------------------------
#
includes/ucp/usercp_viewprofile.php
# 
#-----[ FIND ]---------------------------------
#

require(INC_DIR .'bbcode.php');

# 
#-----[ AFTER, ADD ]---------------------------------
#

require(INC_DIR .'functions_thanks.php');

# 
#-----[ FIND ]---------------------------------
#

	'LOCATION'             => $profiledata['user_from'],

# 
#-----[ AFTER, ADD ]---------------------------------
#

	'USER_THANKS_'         => '<b>' . @get_user_thanks($profiledata['user_id']),
    'USER_THANKED_'        => '<b>' . @get_user_thanked($profiledata['user_id']),

# 
#-----[ OPEN ]---------------------------------
#
 /ajax.php
# 
#-----[ FIND THE LAST  }  AND BEFORE, ADD]---------------------------------
#

	function rate() 
	{
        global $userdata, $lang;
        $attach_id = (int) $this->request['a'];
        $rating = (int) $this->request['v'];

        $result['error'] = false;

        if(is_numeric($rating) && is_numeric($attach_id) && $rating>=1 && $rating<=5) {

            $sql = "insert into ". BB_ATTACHMENTS_RATING ."(attach_id,user_id,rating)values("
                . $attach_id .",". $userdata['user_id'] .",". $rating .")on duplicate key update rating=values(rating)";
            if(DB()->sql_query($sql)) {
                $sql = "select sum(rating) as r, count(*) as c from ". BB_ATTACHMENTS_RATING ." where rating>0 and attach_id=". $attach_id;
                if($res = DB()->sql_query($sql)) {
                    if ($row = DB()->sql_fetchrow($res)) {
                        $result['attach_id'] = $attach_id;
                        $result['rating'] = round($row['r']/$row['c'],1);
                        $result['rating_count'] = $row['c'];
                        $result['your_rating'] = $lang['YOUR_VOTE'] .' '. $lang['RATING_'.$rating] .' '. $lang['VOTE_COUNTED'];
                        $sql = "update ". BB_ATTACHMENTS_DESC ." set rating_sum=". $row['r'] .", rating_count=". $row['c'] ." where attach_id=". $attach_id;
                        DB()->sql_query($sql);
                    }
                    else {
                        $result['error'] = true;
                    }
                }
                else {
                    $result['error'] = true;
                }
            }
            else {
                $result['error'] = true;
            }
        }
        else {
            $result['error'] = true;
        }
        $this->response['message'] = $result;
    }
	
	function thank()
	{
        global $userdata, $lang;
        $mode      = (string) $this->request['m'];
        $attach_id = (int) $this->request['a'];
        if(is_numeric($attach_id)) {
            $result = array('attach_id' => $attach_id, 'error' => false);
            // Thank!
            if($mode == 'thank') {

                $sql = "INSERT INTO ". BB_ATTACHMENTS_RATING ." (attach_id,user_id,thanked) VALUES ("
                    . $attach_id .",". $userdata['user_id'] .",1)on duplicate key update thanked=1";

                if( DB()->sql_query($sql) ) {
                    $sql = "select sum(thanked) as c from ". BB_ATTACHMENTS_RATING ." where attach_id=". $attach_id;

                    if( $res = DB()->sql_query($sql) ) {
                        if ($row = DB()->sql_fetchrow($res)) {
                            $result['thanked'] = $row['c'];
                            $result['mode'] = $mode;
                            $result['list_button']=' &nbsp; (<span id="VL'.$attach_id.'"><a href="#torrent" onClick="thank(\'list\','.$attach_id.');">'. $lang['THANK_LIST'] .'</a></span>)';
                            $sql = "UPDATE ". BB_ATTACHMENTS_DESC ." SET thanks=". $row['c'] ." where attach_id=". $attach_id;
                            DB()->sql_query($sql);
                        }
                        else {
                            $result['error'] = true;
                        }
                    }
                    else {
                        $result['error'] = true;
                    }
                }
                else {
                    $result['error'] = true;
                }
            }
            // Thanks list
            elseif($mode == 'list')
            {
                $sql = DB()->fetch_rowset("SELECT u.user_id, u.username, u.user_rank FROM ". BB_ATTACHMENTS_RATING ." r join ". BB_USERS ." u on u.user_id=r.user_id where r.thanked=1 and r.attach_id=". $attach_id);

                $html = '';
                foreach    ($sql as $row)
                {
                    if( $html ) $html .= ', ';
                    $html .= profile_url($row);
                }
                $result['list'] = $html;
                $result['mode'] = $mode;
            }
            else {
                $result['error'] = true;
            }
        }
        else {
            $result['error'] = true;
        }
        $this->response['message'] = $result;
    }

# 
#-----[ FIND ]---------------------------------
#
	
	'index_data'        => array('guest'),

# 
#-----[ AFTER, ADD ]---------------------------------
#

	'thank'             => array('user'),
    'rate'              => array('user'),
	
#
#-----[ SAVE/CLOSE ALL FILES ]---------------------------------
#
# EoM